package com.wzl.common.exception;

import com.wzl.common.VkPublicResponse;
import com.wzl.common.errcode.VkErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.IOException;
import java.io.Serializable;

/**
 * 全局异常处理类
 *
 * @author weizhongli
 * @since 2022-09-10 00:42
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class VkGlobalExceptionHandler implements Serializable {


    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
    public VkPublicResponse handleHttpMessageNotReadableException(MissingServletRequestParameterException ex){
        log.error("缺少请求参数,{}",ex.getMessage());
        return new VkPublicResponse(VkErrorCodeEnum.FAILED);
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public VkPublicResponse handleTypeMismatchException(NullPointerException ex){
        log.error("空指针异常,{}",ex.getMessage());
        return new VkPublicResponse(VkErrorCodeEnum.ERROR_NULL);
    }

    @ExceptionHandler(ClassCastException.class)
    public VkPublicResponse ClassCastException(ClassCastException ex){
        log.error("类型转换异常,{}",ex.getMessage());
        return new VkPublicResponse(VkErrorCodeEnum.ERROR_CLASS_CAST);
    }

    @ExceptionHandler(IOException.class)
    public VkPublicResponse IOException(IOException ex){
        log.error("上传文件异常,{}",ex.getMessage());
        return new VkPublicResponse(VkErrorCodeEnum.ERROR_IO);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public VkPublicResponse HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex){
        log.error("请求方法错误,{}",ex.getMessage());
        return new VkPublicResponse(VkErrorCodeEnum.ERROR_MOTHOD_NOT_SUPPORT);
    }

    @ExceptionHandler(RuntimeException.class)
    public VkPublicResponse RuntimeException(RuntimeException ex){
        log.error("运行时异常,{}",ex.getMessage());
        return new VkPublicResponse(VkErrorCodeEnum.ERROR_RUNTION);
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public VkPublicResponse handleUnexpectedServer(Exception ex){
        log.error("系统异常：",ex);
        return new VkPublicResponse(VkErrorCodeEnum.ERROR);
    }


}